import compose from './compose';

// middlewares 应用中间件  
// createStore用来创建仓库store，并通过store.dispatch调用中间件  
// reducer
export default function applyMiddleware(...middlewares) {
    return function (createStore){
        return function(reducer, preloadedState){
            let store = createStore(reducer, preloadedState);
            //这里的dispatch 只是为了在middlewareAPI中，提供一个闭包环境，相当于一个wrapper 
            // middlewares在Promise中执行链式调用 pipeline 
            // 如何保证异步非阻塞，一次只能调一个next() ——> 在dispatch($i)包裹下，哨兵指针index与迭代器索引$i 保持长度为1
            let dispatch = () => {
                throw new Error('必须先让dispatch初始化，然后通过dispatch来调用中间件')
            };
            let middlewareAPI = {
                getState: store.getState,
                dispatch: (actions) => dispatch(actions)
            }
            // 拦截dispatch(Action)：把第一个执行参数store.dispatch，通过middlewareAPI，传进中间件链chain
            middlewares = middlewares.map(middleware => middleware(middlewareAPI));
            // middlewareAPI执行的 {state,actions} 会通过store.dispatch调用 reducer(state,actions)更新state
            dispatch = compose(...middlewares)(store.dispatch); //dispatch 会调用reducer(state, action)更新state
            return {...store, dispatch};
        }
    }
}